package com.yunwushanhe.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.yunwushanhe.bean.ret.ResponseResult;
import com.yunwushanhe.constant.Constant;
import com.yunwushanhe.enums.AppHttpCodeEnum;
import com.yunwushanhe.exception.BlogSystemException;
import com.yunwushanhe.service.FileUploadService;
import com.yunwushanhe.util.UUIDUtil;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.Objects;

/**
 * @Author 抬头看看天
 * @Date 2023-08-14  18:51:25
 */

@Data
@Service
@ConfigurationProperties(prefix = "oss")
public class FileUploadServiceImpl implements FileUploadService {

    @Override
    public ResponseResult<String> uploadImag(MultipartFile img) {
        String filename = img.getOriginalFilename();
        if(!StringUtils.hasText(filename) || !filename.endsWith(".jpg")){
            throw new BlogSystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        return ResponseResult.ok(uploadOSS(img));
    }

    private String accessKey;
    private String secretKey;
    private String bucket;

    private String uploadOSS(MultipartFile imgFile){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());

        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = UUIDUtil.getFilePathUUIDName(Objects.requireNonNull(imgFile.getOriginalFilename()));

        try {

            InputStream inputStream = imgFile.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return Constant.PICTURE_PREFIX_PATH +"/"+ key;
    }

}
